$(document).ready(function() {
    let id = location.href.split('?')[1]


    function fuzhi(id) {
        axios({
            method: 'GET',
            url: '/my/article/' + id
        }).then(({ data: res }) => {
            console.log(res);
            if (res.status != 0) {
                return layui.layer.msg(res.message)
            }
            layui.layer.msg(res.message)
            layui.form.val('amendForm', res.data)
            setTimeout(() => {
                tinyMCE.activeEditor.setContent(res.data.content)
            }, 1000)
            let baseURL = 'http://api-breakingnews-web.itheima.net'
            let Url = baseURL + res.data.cover_img
            console.log(Url);
            $image.cropper('destroy').attr('src', Url).cropper(options)
        })
    }

    // 初始化文章分类列表   并封装
    initArtCateList()

    function initArtCateList() {
        axios({
            method: 'GET',
            url: '/my/article/cates'
        }).then(res => {
            // console.log(res);
            if (res.data.status != 0) {
                return layui.layer.msg(res.data.message)
            }
            layui.layer.msg(res.data.message)
            let arr = ['<option value="">请选择文章类别</option>']
            res.data.data.forEach(e => {
                if (e.Id < 0) return
                arr.push(`<option value="${e.Id}">${e.name}</option>`)
            })
            $('[name=cate_id]').empty().html(arr.join(''))
                // layui的表单需要调用此方法才能渲染
            layui.form.render()
            fuzhi(id)
        })
    }

    //修改
    $('#amendForm').on('submit', function(e) {
        e.preventDefault()
        let fd = new FormData(this)
            // alert(state)
        fd.append('state', state)
            // console.log(...fd)
        $image
            .cropper('getCroppedCanvas', { // 创建一个 Canvas 画布
                width: 400,
                height: 280
            })
            .toBlob(function(blob) { // 将 Canvas 画布上的内容，转化为文件对象
                // 得到文件对象后，进行后续的操作
                // console.log(blob);
                fd.append('cover_img', blob)
                console.log(...fd)
                axios({
                    method: 'POST',
                    url: '/my/article/edit',
                    data: fd
                }).then(res => {
                    if (res.data.status != 0) {
                        return layui.layer.msg(res.data.message)
                    }
                    if (state == '已发布') {
                        layui.layer.msg('修改成功')
                    } else {
                        layui.layer.msg('已存为草稿')
                    }

                    // $('#pubForm')[0].reset()
                    setTimeout(function() {
                        window.parent.layer.closeAll()
                    }, 1500)
                })
            })
    })


})